package io.terminus.paas.profiler.utils

import com.alibaba.dubbo.common.Constants
import com.alibaba.dubbo.common.utils.StringUtils
import java.net.URLDecoder
import java.text.ParseException
import java.util.*

/**
 * Created by gengrong on 16/3/18.
 */
object ConvertUtil {
    fun convertRegister(register: Map<String, HashMap<String, String>>): HashMap<String, HashMap<String, String>> {
        val newRegister = hashMapOf<String, HashMap<String, String>>()
        for ((serviceName, serviceUrls) in register) {
            if (!serviceName.contains(":") && !serviceName.contains("/")) {
                for ((serviceUrl, serviceQuery) in serviceUrls) {
                    val params = StringUtils.parseQueryString(serviceQuery)
                    val group = params["group"]
                    val version = params["version"]
                    params.remove("group")
                    params.remove("version")
                    var name = serviceName
                    if (group != null && group.length > 0) {
                        name = group + "/" + name
                    }
                    if (version != null && version.length > 0 && "0.0.0" != version) {
                        name = name + ":" + version
                    }
                    var newUrls = newRegister[name]
                    if (newUrls == null) {
                        newUrls = HashMap<String, String>()
                        newRegister.put(name, newUrls)
                    }
                    newUrls.put(serviceUrl, StringUtils.toQueryString(params))
                }
            } else {
                newRegister.put(serviceName, serviceUrls)
            }
        }
        return newRegister
    }

    fun serviceName2Map(serviceId: String): Map<String, String> {
        var serviceName = serviceId
        var group: String? = null
        var version: String? = null
        var i = serviceName.indexOf("/")
        if (i > 0) {
            group = serviceName.substring(0, i)
            serviceName = serviceName.substring(i + 1)
        }
        i = serviceName.lastIndexOf(":")
        if (i > 0) {
            version = serviceName.substring(i + 1)
            serviceName = serviceName.substring(0, i)
        }

        val ret = HashMap<String, String>()
        if (!StringUtils.isEmpty(serviceName)) {
            ret.put(Constants.INTERFACE_KEY, serviceName)
        }
        if (version != null && version.isNotEmpty()) {
            ret.put(Constants.VERSION_KEY, version)
        }
        if (group != null && group.isNotEmpty()) {
            ret.put(Constants.GROUP_KEY, group)
        }

        return ret
    }

    fun decode(str: String?): String? {
        return URLDecoder.decode(str, "UTF-8");
    }


    class MatchPair {
        var matches= hashSetOf<String>()
        var unmatches= hashSetOf<String>()
    }

    fun parseRule(rule: String): Map<String, MatchPair> {
        val condition = HashMap<String, MatchPair>()
        if (StringUtils.isBlank(rule)) {
            return condition
        }
        // 匹配或不匹配Key-Value对
        var pair: MatchPair? = null
        // 多个Value值
        var values: MutableSet<String>? = null
        val matcher = ProfilerConstants.ROUTE_PATTERN.matcher(rule)
        while (matcher.find()) {
            // 逐个匹配
            val separator = matcher.group(1)
            val content = matcher.group(2)
            // 表达式开始
            if (separator == null || separator.length == 0) {
                pair = MatchPair()
                condition.put(content, pair)
            } else if ("&" == separator) {
                if (condition[content] == null) {
                    pair = MatchPair()
                    condition.put(content, pair)
                } else {
                    condition.put(content, pair!!)
                }

            } else if ("=" == separator) {
                if (pair == null)
                    throw ParseException("Illegal route rule \""
                            + rule + "\", The error char '" + separator
                            + "' at index " + matcher.start() + " before \""
                            + content + "\".", matcher.start())

                values = pair.matches
                values.add(content)
            } else if ("!=" == separator) {
                if (pair == null)
                    throw ParseException("Illegal route rule \""
                            + rule + "\", The error char '" + separator
                            + "' at index " + matcher.start() + " before \""
                            + content + "\".", matcher.start())

                values = pair.unmatches
                values.add(content)
            } else if ("," == separator) {
                // 如果为逗号表示
                if (values == null || values.size == 0)
                    throw ParseException("Illegal route rule \""
                            + rule + "\", The error char '" + separator
                            + "' at index " + matcher.start() + " before \""
                            + content + "\".", matcher.start())
                values.add(content)
            } else {
                throw ParseException("Illegal route rule \"" + rule
                        + "\", The error char '" + separator + "' at index "
                        + matcher.start() + " before \"" + content + "\".", matcher.start())
            }// KV的Value部分的多个条目
            // KV的Value部分开始
            // KV的Value部分开始
            // KV开始
        }
        return condition
    }
}